﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;

namespace RestfulApiV1.Utils.Json
{
    public class JsonHelper
    {
        /// <summary>
        /// 序列化对象为Json字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string SerializeObject(object obj)
        {
            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                DateFormatString="yyyy-MM-dd HH:mm:ss",
                ReferenceLoopHandling=ReferenceLoopHandling.Ignore,
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            };

            return JsonConvert.SerializeObject(obj,Formatting.Indented,settings);
        }

        /// <summary>
        /// 反序列化JObject对象为dynamic对象
        /// </summary>
        /// <param name="jObject"></param>
        /// <returns></returns>
        //public static dynamic DeserializeDynamic(JObject jObject)
        //{
        //    var str = JsonHelper.SerializeObject(jObject);

        //    return JsonConvert.DeserializeObject<dynamic>(str);
        //}

        /// <summary>
        /// 反序列化字符串为dynamic对象
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static dynamic DeserializeDynamic(dynamic obj)
        {
            string str = SerializeObject(obj);
            return JsonConvert.DeserializeObject<dynamic>(str);
        }
    }
}
